const request = require('request');
const dotenv= require("dotenv");
dotenv.config({ path: `.env.${process.env.NODE_ENV}` })
const CryptoJS = require("crypto-js");
let sign_salt = "N8bikO00SGQ3MxxzvYzhe2luyPN0OXc4";
let comkey = "fcb7a03dad8048e3879c838a82a31c5c";
let appId = "ZvOuxZkqhGXeIrtfJVvVlbOwJC6lQw";
let baseurl = "https://ivrvapi.daikin.net.cn";
const Redis = require("ioredis");
const redis = new Redis({
    port: process.env.REDIS_PORT,
    host: process.env.REDIS_HOST,
    db: process.env.REDIS_DB,
    password: process.env.REDIS_PASSWORD
})
var gf = {
    encryptData: function (paramData) {
        var key = comkey;
        let keyHex = CryptoJS.enc.Utf8.parse(key);
        let txtHex = CryptoJS.enc.Utf8.parse(paramData);
        var encrypted = CryptoJS.AES.encrypt(txtHex, keyHex, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        })
            .toString();
        console.log('paramData:' + paramData + ',encryptData:' + encrypted);
        return encrypted;
    },
    setSignData: function (jsonData) {
        var keys = [];
        for (let k in jsonData) {
            if (k == 'sign') {
                continue;
            }
            keys.push(k);
        }
        keys.sort();
        var signStr = '';
        for (let k of keys) {
            signStr += k;
            if (typeof jsonData[k] === 'object') {
                signStr += JSON.stringify(jsonData[k]);
            } else if (typeof jsonData[k] === 'string' && jsonData[k].indexOf('{{') != -1) {
                temp = jsonData[k].replace('{{', '');
                temp = temp.replace('}}', '');
                signStr += temp;
            } else {
                signStr += jsonData[k];
            }
        }
        signStr += sign_salt;
        console.log('signStr⇒' + signStr);
        var sign_utf8 = CryptoJS.enc.Utf8.parse(signStr);
        var sign = CryptoJS.MD5(sign_utf8)
            .toString()
            .toUpperCase();
        console.log('sign⇒' + sign);
        return sign;
    }
}
function doRequestPost(url, json, token) {
    let body_param = JSON.stringify(json);
    let data = gf.encryptData(body_param);
    const options = {
        method: 'POST',
        url: url,
        headers: {
            'Content-Type': 'application/json',
            appId: appId,
            sign: gf.setSignData(json),
            token: token
        },
        body: data
    };
    return new Promise(function (resolve, reject) {
        request(options, function (error, res, body) {
            if (!error && res.statusCode === 200) {
                resolve(body);
            } else {
                reject(error);
            }
        });
    });
}
module.exports = {
    getToken: async function () {
        let token = await redis.get("dajin_token");
        if (!token) {
            try {
                let json = { "pass": "38928bfdf1514966b0d28d711a2302f3" };
                let data = await doRequestPost("https://ivrvapi.daikin.net.cn/token", json);
                data = JSON.parse(data);
                if (data && data.code == "10000") {
                    await redis.set("dajin_token", data.data.token, 'EX', 3599);
                    await redis.set("dajin_refreshKey", data.data.refreshKey, 'EX', 3599);
                    token = data.data.token
                }
            } catch (e) {
                return false;
            }

        }
        return token;
    },
    getQuality: async function () {
        let token = await this.getToken();
        let result = null;
        let json = [{
            "macAddress": "6018030FC415",
            "sensorMac": "3CE90E418DF4"
        }];//D5一楼大厅
        if (token) {
            try {
                let data = await doRequestPost("https://ivrvapi.daikin.net.cn/v2/airQualityOpenPanel", json, token);
                data=JSON.parse(data);
                if(data.code=="10000"){
                    result= data.data;
                }
                console.log(data);
            } catch (e) {
                return null;
            }
            return result;
        }
    }
}